package com.hnevc.photodemo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.theartofdev.edmodo.cropper.CropImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Uri imageUri;
    private Uri resultUri;
    private String realFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //TODO 拍照
    //takephoto 将会在Button点击的时候调用
    public void takePhoto(View view) throws IOException {
        //1 准备Uri
            //保存拍照之后的结果文件,必须是一个新文件
        File file = new File(getExternalCacheDir(),"image.jpg");
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();
            //将file转换为Uri
        if(Build.VERSION.SDK_INT>=24){
            imageUri = FileProvider.getUriForFile(this
                    ,"com.hnevc.photodemo.fileprovider"
                    ,file);
        }else {
            imageUri = Uri.fromFile(file);
        }
        //2 启动拍照程序
            //创建一个隐式意图，调用拍照程序
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            //指定拍照程序照片存放的文件Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            //是有那个请求码101，启动拍照程序
        startActivityForResult(intent,101);
    }
    //TODO 裁切
    public void cropPhoto(View view){
        CropImage.activity(imageUri) .start(this);

    }
    //TODO 上传
    public void uploadPhoto(View view) {
        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //准备上传得文件对象file
                String s = resultUri.toString();
                Log.e(TAG,"run:"+s);
                    URI uri = new URI(s);
                    File file = new File(uri);
                    //构建一个MultipartBody
                        //(1)构建ResquestBody
                    RequestBody body = RequestBody.create(MediaType.parse("image/png"),file);
                        //(2)构建MultiparBody
                    MultipartBody multipartBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("file","image.jpg",body)
                            .build();
                        //构建请求Request对象
                    Request request = new Request.Builder()
                            .url("http://10.1.63.232:8080/RestaurantServer/File/doUpload")
                            .post(multipartBody)
                            .build();
                        //执行请求，处理结果
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    String data = response.body().string();
                    //将data转换为jsonobject
                    JSONObject jsonObject = new JSONObject(data);
                    realFileName = jsonObject.getString("realFileName");



                    Log.e(TAG,"run:"+ data);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //TODO 添加食物
    public void addFood(View view) throws JSONException {
        //获取用户输入的数据，构建上传得数据json字符串，完成上传，并处理结果
        EditText etFoodName = (EditText) findViewById(R.id.id_et_food_name);
        EditText etFoodPrice = (EditText)findViewById(R.id.id_et_food_price);
        EditText etFoodDesc = (EditText)findViewById(R.id.id_et_food_desc);

        String foodName = etFoodName.getText().toString();
        String sfoodPrice = etFoodPrice.getText().toString();
        int foodPrice = Integer.parseInt(sfoodPrice);
        String foodDesc = etFoodDesc.getText().toString();
        String foodPic = realFileName;//图片文件的名字,利用字段变量共享数据

        //准备json
        JSONObject object = new JSONObject();
        object.put("foodName",foodName);
        object.put("foodPrice",foodPrice);
        object.put("foodDesc",foodDesc);
        object.put("foodPic",foodPic);
        final String jsons = object.toString();//将json对象转换为jsons字符串

        //完成上传
        new Thread(new Runnable() {
            @Override
            public void run() {
                //创建客户端对象
                OkHttpClient client = new OkHttpClient();

                RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsons);
                String url = "http://10.1.63.232:8080/RestaurantServer/Food/addFood";

                Request request = new Request.Builder()
                        .url(url)//网址
                        .post(body)//提交的数据
                        .build();

                try {
                    Response response = client.newCall(request).execute();//发送请求，获取结果
                    String data = response.body().string();
                    Log.e(TAG,"run:"+data);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //通过requestCode请求码来区分不同的Activity的返回结果
        if(requestCode==101) {//拍照

            //resultCode 表明目标Activity的执行结果状态
            if (resultCode == RESULT_OK) {
                try {
                    //通过contentResolver，获取Uri对象的字节流
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    //从输入流，构造bitmap
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    //从布局文件中，获取显示图片的ImageView
                    ImageView photoImage = (ImageView) findViewById(R.id.id_iv_photo);
                    //将bitmap显示到photoImage中
                    photoImage.setImageBitmap(bitmap);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "取消了", Toast.LENGTH_SHORT).show();
            }
        }

        if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) //裁切的结果
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            resultUri = result.getUri();
            //通过contentResolver，获取Uri对象的字节流
            InputStream inputStream = null;
            try {
                inputStream = getContentResolver().openInputStream(resultUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            //从输入流，构造bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            //从布局文件中，获取显示图片的ImageView
            ImageView photoImage = (ImageView) findViewById(R.id.id_iv_photo);
            //将bitmap显示到photoImage中
            photoImage.setImageBitmap(bitmap);


        }

    }
}
